<template>
    <a-layout-content style="padding: 0 14px; margin: 50px 0">
        <a-layout style="padding: 14px 0; background: #fff">
            <a-layout-content :style="{ padding: '0 24px', minHeight: '900px' }">

                <a-row :gutter="24">
                    <a-col :span="6" >
                        <p>
                            <a-form layout="inline" :model="param">
                                <a-form-item>
                                    <a-button type="primary" @click="handleQuery()">
                                        查询
                                    </a-button>
                                </a-form-item>
                                <a-form-item>
                                    <a-button type="primary" @click="add()">
                                        新增
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </p>
                        <a-table
                                v-if="level1.length>0"
                                :columns="columns"
                                :row-key="record => record.id"
                                :data-source="level1"
                                :loading="loading"
                                :pagination="false"
                                size="small"
                                :defaultExpandAllRows="true"
                        >

                            <template #name="{ text, record }">
                                {{record.sort}} - {{text}}
                            </template>


                            <template v-slot:action="{ text : record }">
                                <a-space size="small">
                                    <a-button type="primary" size="small"  @click="edit(record)" >
                                        编辑
                                    </a-button>
                                    <a-popconfirm
                                            title="是否删除?"
                                            ok-text="Yes"
                                            cancel-text="No"
                                            @confirm="Bdelete(record)"
                                    >
                                        <a-button type="danger"  size="small">
                                            删除
                                        </a-button>
                                    </a-popconfirm>

                                </a-space>
                            </template>
                        </a-table>
                    </a-col>
                    <a-col :span="18">
                        <a-form :model="doc" layout="vertical"  >

                            <a-form-item>
                                <a-button type="primary" size="small"  @click="handleSave(record)" >
                                    保存
                                </a-button>
                            </a-form-item>

                            <a-form-item >
                                <a-input v-model:value="doc.name" placeholder="名称" />
                            </a-form-item>
                            <a-form-item >
                                <a-tree-select
                                        v-model:value="doc.parent"
                                        style="width: 100%"
                                        :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
                                        :tree-data="treeSelectData"
                                        placeholder="请选择父文档"
                                        tree-default-expand-all
                                        :replaceFields="{children:'children', title:'name', key:'id', value: 'id' }"
                                >
                                </a-tree-select>

                            </a-form-item>
                            <a-form-item >
                                <a-input v-model:value="doc.sort" placeholder="排序" />
                            </a-form-item>
                            <a-form-item>
                                <a-button type="primary" size="small"  @click="handlePreviewContent()" >
                                   <EyeOutlined /> 预览内容
                                </a-button>
                            </a-form-item>
                            <a-form-item >
                                <div id="content_doc"></div>
                            </a-form-item>
                        </a-form>
                    </a-col>
                </a-row>
                <!--                渲染数据s              -->

                <!--                渲染数据e              -->
            </a-layout-content>
        </a-layout>
    </a-layout-content>

<!--    <a-modal title="文档表单"  v-model:visible="modelVisible"-->
    <!--             :confirm-loading="modelLoading"-->
    <!--              @ok="handleModelOk">-->
    <!--           -->
<!--    </a-modal>-->

    <a-drawer
            width="90%"
            placement="right"
            :closable="false"
            v-model:visible="drawerVisible"
    >

        <div  class="m_wangeditor" :innerHTML="html"></div>
    </a-drawer>
</template>
<script lang="ts">

    import {defineComponent, onMounted, ref,createVNode} from 'vue';
    import axios from 'axios';
    import {message, Modal} from 'ant-design-vue';
    import {Tool} from "@/util/tool";
    import {useRoute} from "vue-router";
    import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
    import E from 'wangeditor'

    export default defineComponent({
        name: 'AdminDoc',
        setup: function () { //入口
            console.log("setup");
            const route = useRoute();
            const param = ref();
            param.value = {};  //存储请求时要 过滤参数数据
            const docs = ref();//声明动态数据
            const level1 = ref();
            level1.value = []
            const treeSelectData = ref();
            treeSelectData.value = [];
            const columns = [
                {
                    title: '名称',
                    dataIndex: 'name',
                    slots: {customRender: 'name'}
                },
                {
                    title: '操作',
                    key: 'action',//没有的数据加key
                    slots: {customRender: 'action'}
                }
            ]; //对应列

            const loading = ref(false); //页面加载
            let editor: any;

            //表单
            const doc = ref();
            doc.value = {
                ebookId: route.query.ebookId
            }
            const modelLoading = ref<boolean>(false);
            const modelVisible = ref<boolean>(false);

            const handleSave = () => {
                modelLoading.value = true;
                doc.value.content = editor.txt.html();
                axios.post("/doc/save", doc.value).then((response) => {

                    const data = response.data;
                    if (data.success) {
                        editor.txt.html('')
                        // modelLoading.value = false;
                        // modelVisible.value = false;
                        message.success("保存成功！")
                        handleQuery();
                    } else {
                        modelLoading.value = false;
                        message.error(data.message)
                    }
                    doc.value = {
                        ebookId: route.query.ebookId
                    }
                });
            };
            const edit = (record: any) => {
                editor.txt.html('')
                modelVisible.value = true;
                doc.value = Tool.copy(record);
                //查询内容
                handleContent();

                treeSelectData.value = Tool.copy(level1.value);

                //为选择树增加一个“无”
                treeSelectData.value.unshift({id: 0, name: '无'})

                //不能选择当前节点及其所有的子孙节点
                setDisable(treeSelectData.value, record.id);
            };

            const add = () => {
                editor.txt.html('')
                modelVisible.value = true;
                doc.value = {
                    ebookId: route.query.ebookId
                }
                treeSelectData.value = Tool.copy(level1.value) || [];

                //为选择树增加一个“无”
                treeSelectData.value.unshift({id: 0, name: '无'})
            };

            const Bdelete = (record: any) => {
                ids = [] , names = [];
                getDeleteIds(level1.value, record.id)
                Modal.confirm({
                    title: '是否删除?',
                    icon: createVNode(ExclamationCircleOutlined),
                    content: '删除' + names.join(","),
                    okText: '是',
                    okType: 'danger',
                    cancelText: '否',
                    onOk() {
                        axios.delete("/doc/delete/" + ids.join(",")).then((response) => {
                            const data = response.data;
                            if (data.success) {
                                handleQuery();
                            }
                        });
                    },
                });

            };

            /**
             * 数据查询
             **/
            const handleQuery = () => {
                loading.value = true;
                axios.get("/doc/all/"+route.query.ebookId).then((response) => {
                    loading.value = false;
                    const data = response.data;
                    if (data.success) {
                        docs.value = data.content; //

                        level1.value = [];
                        level1.value = Tool.array2Tree(docs.value, 0)

                        //初始化时就可以选择
                        treeSelectData.value = Tool.copy(level1.value);
                        //为选择树增加一个“无”
                        treeSelectData.value.unshift({id: 0, name: '无'})
                    } else {
                        message.error(data.message);
                    }
                });
            };


            /**
             * 查询文档内容
             **/
            const handleContent = () => {
                axios.get("/doc/find_content/"+doc.value.id).then((response) => {
                    const data = response.data;
                    if (data.success) {
                        editor.txt.html(data.content==null ? '' : data.content.content)
                    } else {
                        message.error(data.message);
                    }
                });
            };


            const setDisable = (treeSelectData: any, id: any) => {

                for (let i = 0; i < treeSelectData.length; i++) {
                    const node = treeSelectData[i];
                    if (node.id === id) {
                        node.disabled = true;

                        //遍历所有子节点加上disabled
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            for (let j = 0; j < children.length; j++) {
                                setDisable(children, children[j].id)
                            }
                        }
                    } else {
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            setDisable(children, id)
                        }
                    }
                }
            };

            let ids: Array<string> = [];
            let names: Array<string> = [];

            const getDeleteIds = (treeSelectData: any, id: any) => {

                for (let i = 0; i < treeSelectData.length; i++) {
                    const node = treeSelectData[i];
                    if (node.id === id) {
                        ids.push(id);
                        names.push(node.name)
                        //遍历所有子节点加上disabled
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            for (let j = 0; j < children.length; j++) {
                                getDeleteIds(children, children[j].id)
                            }
                        }
                    } else {
                        const children = node.children;
                        if (Tool.isNotEmpty(children)) {
                            getDeleteIds(children, id)
                        }
                    }
                }
            };

            const drawerVisible = ref(false);
            const html = ref();
            const handlePreviewContent = () => {
                html.value=editor.txt.html();
                drawerVisible.value=true
            };


            onMounted(() => {
                handleQuery();
                setTimeout(function () {
                    editor = new E('#content_doc');
                    editor.create();
                }, 200)
            });

            return {
                columns,
                docs,
                loading,
                modelLoading,
                modelVisible,
                edit,
                Bdelete,
                add,
                handleSave,
                doc,
                handleQuery,
                param,
                level1,
                treeSelectData,
                handlePreviewContent,
                drawerVisible,
                html
            };
        },
    });
</script>

<!--scoped 只在当前页面生效-->
<style scoped>
    #content_doc >>> .w-e-toolbar{
        z-index: 1 !important;
    }
    #content_doc >>> .w-e-text-container{
        z-index: 0 !important;
        height: 500px !important;
    }

    /* table 样式 */
    .m_wangeditor >>> table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
    }
    .m_wangeditor >>> table td,
    .m_wangeditor >>> table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        padding: 3px 5px;
    }
    .m_wangeditor >>> table th {
        border-bottom: 2px solid #ccc;
        text-align: center;
    }

    /* blockquote 样式 */
    .m_wangeditor >>> blockquote {
        display: block;
        border-left: 8px solid #d0e5f2;
        padding: 5px 10px;
        margin: 10px 0;
        line-height: 1.4;
        font-size: 100%;
        background-color: #f1f1f1;
    }

    /* code 样式 */
    .m_wangeditor >>> code {
        display: inline-block;
        *display: inline;
        *zoom: 1;
        background-color: #f1f1f1;
        border-radius: 3px;
        padding: 3px 5px;
        margin: 0 3px;
    }
    .m_wangeditor >>> pre code {
        display: block;
    }

    /* ul ol 样式 */
    .m_wangeditor >>> ul,  .m_wangeditor  >>>ol {
        margin: 10px 0 10px 20px;
    }
</style>
